package models.baseinfo

import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import slick.jdbc.JdbcProfile

import java.sql.Timestamp
import javax.inject.Inject
import scala.concurrent.ExecutionContext

class KDCustomerCodeRepository @Inject()(protected val dbConfigProvider: DatabaseConfigProvider)(implicit executionContext: ExecutionContext)
  extends HasDatabaseConfigProvider[JdbcProfile] {

  import dbConfig._
  import profile.api._

  private class KDCustomerCodeTable(tag: Tag)
    extends Table[CustomerCode](tag, "IMED_CUSTOMERCODE") {
    def id = column[Long]("ID", O.PrimaryKey)

    def code = column[String]("CODE")

    def name = column[String]("NAME")

    def kdId = column[Int]("KDID")

    def kdNo = column[String]("KDNUMBER")

    def kdName = column[String]("KDNAME")

    def status = column[Boolean]("STATUS")

    def org = column[String]("ORG")

    def deptId = column[String]("DEPTID")

    def upDate = column[Timestamp]("UP_DATE")

    def * =
      (id, code, name, kdId, kdNo, kdName, status, org, deptId, upDate)
        .<>((CustomerCode.apply _).tupled, CustomerCode.unapply)
  }

  private val customerTable = TableQuery[KDCustomerCodeTable]

  def insert(kd: CustomerCode) = db.run {
    customerTable.filter(_.id === kd.id).result
  }.flatMap {
    r =>
      db.run {
        if (r.isEmpty) {
          customerTable returning customerTable.map(_.id) += kd
        } else {
          customerTable.filter(_.id === kd.id)
            .map(f => (f.name, f.code))
            .update((kd.name, kd.code))
        }
      }
  }

  def updateKdInfo(kd: CustomerCode) = db.run {
    customerTable.filter(_.kdId === kd.kdId)
      .map(f => (f.kdNo, f.kdName, f.org,f.upDate))
      .update((kd.kdNo, kd.kdName, kd.org,kd.upDate))
  }

  def insertKdInfo(kd:CustomerCode)= db.run{
    customerTable.filter(_.code === kd.code)
      .map(f=>(f.kdId,f.kdNo,f.kdName,f.org))
      .update((kd.kdId,kd.kdNo,kd.kdName,kd.org))
  }

  def list = db.run {
    customerTable.map(f => f).result
  }

}
